/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core;

import datamodel.Message;
import datamodel.StorageInformer;
import datastorage.MessageManagerStorage;
import java.util.Vector;
import network.Connection;
import network.packets.Packet;
import network.packets.TCPMessageResponce;

/**
 *
 * @author Kvest
 */
public class MessageManager 
{
    public static final int DEFAULT_MAX_MESSAGES_COUNT = 50;
    
    private MessageManagerStorage storage;
    
    private CountChanged countChangedListener;
    private MessageEvents messageEventsListener;
    
    private final Vector messages = new Vector();
    private int maxMessagesdCount = DEFAULT_MAX_MESSAGES_COUNT;
    
    public MessageManager()
    {
        storage = new MessageManagerStorage();
        
        load();
        
        registerNetworkNotifiers();
    }    
    
    public final void load()
    {
        clear();
        
        synchronized(messages)
        {
            storage.load(messages);
        }
    }
    
    public void save()
    {
        synchronized(messages)
        {
            storage.save(messages);
        }
    }
    
    public void clear()
    {
        synchronized(messages)
        {
            messages.removeAllElements();
        }
    }
    
    public void deleteAll()
    {
        //Удалям все из памяти
        clear();
        
        //Удаляем все с RMS
        storage.clear();
    }
    
    public void messageWasRead(Message message)
    {
        //Помечаем как прочтенное
        message.setRead(true);
        
        //Просто обновляем количество - остольное обновится само
        countChangedEvent();
    }
    
    public void setMaxMessagesdCount(int maxMessagesdCount) {
        this.maxMessagesdCount = maxMessagesdCount;
    }
    
    public StorageInformer getStorageMemoryInfo()
    {
        return storage;
    }
    
    public Vector getAllMessages()
    {
        Vector result = new Vector();
        synchronized(messages)
        {
            for(int i = 0; i < messages.size(); ++i)
            {
                result.addElement(messages.elementAt(i));
            }
        }
        
        return result;
    }
    
    public void newMessage(Message message)
    {
        synchronized(messages)
        {
            messages.insertElementAt(message, 0);
            while (messages.size() > maxMessagesdCount) {
                messages.removeElementAt(messages.size() - 1);
            }
        }
        
        //Генерируем события
        newMessageEvent(message);
        countChangedEvent();
    }
    
    private int getTotalCount()
    {
        synchronized(messages)
        {
            return messages.size();
        }
    }
    
    private int getNewCount()
    {
        int result = 0;
        synchronized(messages)
        {
            for (int i = 0; i < messages.size(); ++i)
            {
                if (!((Message)messages.elementAt(i)).isRead())
                {
                    ++result;
                }
            }
        }
        
        return result;
    }
    
    private void registerNetworkNotifiers()
    {
        Connection.getConnection().setPacketListener(Packet.TCPMESSAGE_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                TCPMessageResponce responce = (TCPMessageResponce)packet;
                
                //Проверяем, не отмена ли это заказа
                if (responce.getClassName().equals(TCPMessageResponce.CANCEL_ORDER_CLASS_NAME))
                {
                    IMAPMIDlet.getMidlet().getOrderManager().cancelOrder(responce.getOrderID());
                }
                
                newMessage(new Message(responce.getMessage(), responce.getFrom(), responce.getTo()));
            }
        });
    }
    
    public void setCountChangedListener(CountChanged countChangedListener) 
    {
        this.countChangedListener = countChangedListener;
        
        //Сразу генерируем событие
        countChangedEvent();
    }

    public void setMessageEventsListener(MessageEvents messageEventsListener) 
    {
        this.messageEventsListener = messageEventsListener;
    }

    private void countChangedEvent()
    {
        if (countChangedListener != null)
        {
            countChangedListener.countChanged(getNewCount(), getTotalCount());
        }
    }
    
    private void newMessageEvent(Message message)
    {
        //Оповещение
        NotificationManager.getNotificationManager().event(NotificationManager.NEW_MESSAGE);
        
        if (messageEventsListener != null)
        {
            messageEventsListener.newMessage(message);
        }
    }
    
    public interface CountChanged
    {
        public void countChanged(int newMessagesCount, int totalMessagesCount);
    }
    
    public interface MessageEvents
    {
        public void newMessage(Message message);
    }
}
